import { createRouter, createWebHashHistory } from "vue-router"
import { useLoginStore } from "@/store/loginStore"
import { ElMessage } from "element-plus"

import { DataManagerRoute } from "./data-manager-routes"

const routes = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/Login.vue")
  },
  {
    path: "/",
    name: "home",
    component: () => import("../views/Home.vue")
  },
  {
    path: "/:catchAll(.*)",
    name: "404",
    component: () => import("../views/404.vue")
  },
  DataManagerRoute
]

const router = createRouter({
  history: createWebHashHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.name === "404") {
    next()
    return
  }
  const loginStore = useLoginStore()
  if (to.name === "login") {
    if (loginStore.isAuthenticated()) {
      ElMessage.error("你已经登录过了")
      next("/")
    } else {
      next()
    }
    return
  } else if (to.name !== "home") {
    if (!loginStore.isAuthenticated()) {
      ElMessage.error("请登录后再试")
      next("/login")
    } else {
      next()
    }
    return
  }
  next()
})



export default router
